package cn.fanqinghong.pet.service.impl;

import cn.fanqinghong.basic.exception.BusinessException;
import cn.fanqinghong.basic.service.impl.BaseServiceImpl;
import cn.fanqinghong.basic.util.*;
import cn.fanqinghong.org.domain.Shop;
import cn.fanqinghong.org.mapper.ShopMapper;
import cn.fanqinghong.pet.domain.*;
import cn.fanqinghong.pet.dto.HandleMsgDto;
import cn.fanqinghong.pet.mapper.OrderPetAcquisitionMapper;
import cn.fanqinghong.pet.mapper.PetMapper;
import cn.fanqinghong.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.fanqinghong.pet.mapper.SearchMasterMsgMapper;
import cn.fanqinghong.pet.service.ISearchMasterMsgService;
import cn.fanqinghong.user.domain.Logininfo;
import cn.fanqinghong.user.domain.User;
import cn.fanqinghong.user.mapper.UserMapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fanqinghong
 * @since 2022-06-28
 */
@Service
@Slf4j
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    /**
     * 宠物寻主
     * @param msg
     * @param logininfo
     */
    @Override
    public void publish(SearchMasterMsg msg, Logininfo logininfo) {
        //获得到用户的消息
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //一.保存寻主消息
        //.设置msg表中的UserId字段
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);
        //二：审核
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        //1.系统自动审核
        if (!BaiduAuditUtils.TextCensor(msg.getName())){
            //.系统审核不通过，保存状态码，返回审核不通过的信息，发送短信

            //设置状态码为0，审核失败
            msg.setState(0);
            msg.setName("审核失败，内容包含敏感字符，请重新发布！！");
            //设置审核日志的msgId
            log.setMsgId(msg.getId());
            //记录审核日志
            log.setNote("审核失败，内容包含敏感字符，请重新发布！！");
        }else{
            //.审核通过，保存状态码，
            msg.setState(1);
            msg.setNote("审核通过");
            log.setState(1);
            log.setNote("审核通过");
            //审核通过，定位发布人的地址，
            Point point = DistanceUtil.getPoint(msg.getAddress());
            //查询五十公里内的所有店铺，找到最近的店铺
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop!=null){
                //找到了店铺，绑定店铺ID
                msg.setShopId(nearestShop.getId());
                //审核通过记录日志
                //SmsUtils.sendSms(user.getPhone(),"亲爱的老板："+nearestShop.getName()+"，你的店铺收到新的信息，请赶快出来接客！！");
            }
                //没有找到店铺，不绑定店铺id,把信息放到宠物池,展示不管@todo
        }
        searchMasterMsgAuditLogMapper.save(log);
        searchMasterMsgMapper.update(msg);
        //2.人工审核  @TODO
        //2.1 风控系统---系统自动通过约定的规则去审核
        //2.2 部分信息可能需要人工接入审核

    }

    /**
     * 接单
     * @param dto
     */
    @Override
    public void accept(HandleMsgDto dto) {
        //判断当前订单是否时非取消或者没有被别人接单
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgIdAndCancel(dto.getMsgId());
        if (order != null){
            throw new BusinessException("该订单已经被接单！！！");
        }
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(dto.getMsgId());
        //1.录入宠物
        Pet pet = initPet(dto,msg);
        petMapper.save(pet);
        //2.录入接单信息
        order = initOrderPetAcquisition(dto,msg,pet);
        //保存订单
        orderPetAcquisitionMapper.save(order);


    }

    /**
     * 录入接单信息
     * @param dto
     * @param msg
     * @param pet
     * @return
     */
    private OrderPetAcquisition initOrderPetAcquisition(HandleMsgDto dto, SearchMasterMsg msg, Pet pet) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        //订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getHandler()));
        //摘要
        order.setDigest(pet.getName()+"的订单,摘要"+dto.getNote());
        //过期时间
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+24*60*60*1000));
        order.setPetId(pet.getId());
        //宠物寻主发布者的ID
        order.setUserId(msg.getUserId());
        //接单店铺id
        order.setShopId(msg.getShopId());
        //上门地址
        order.setAddress(msg.getAddress());
        //店员id//3.绑定店铺收购人员
        order.setEmpId(dto.getHandler());
        //宠物寻主ID
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }

    /**
     * 录入宠物信息
     * @param dto
     * @param msg
     * @return
     */
    private Pet initPet(HandleMsgDto dto,SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());//宠物的名字，使用寻主信息中的名字
        pet.setTypeId(msg.getPetType());//宠物的种类id，寻主信息中的种类id
        pet.setShopId(msg.getShopId());//绑定店铺id，寻主信息中的shopId
        pet.setSearchMasterMsgId(msg.getId());//寻主信息Id
        return pet;
    }
}
